package com.wushijia.highconcurrency.threadlocal;

import java.math.BigDecimal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * InheritableThreadLocal:可继承的ThreadLocal
 *
 * @author Administrator
 * @date 2021-06-01 14:48
 */
public class InheritableThreadLocalDemo1 {

  static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

  public static void main(String[] args) throws InterruptedException {
    //main1();

    System.out.println(("hh".hashCode() % 16) == ("hh".hashCode() & 15));
    System.out.println(BigDecimal.valueOf(Double.parseDouble("11.28")).divide(BigDecimal.valueOf(100)));
    main2();
  }

  public static void main1() throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(1);

    inheritableThreadLocal.set("i am a inherit parent");
    executorService.execute(new Runnable() {
      @Override
      public void run() {
        System.out.println(inheritableThreadLocal.get());//i am a inherit parent
      }
    });

    TimeUnit.SECONDS.sleep(1);
    inheritableThreadLocal.set("i am a new inherit parent");// 设置新的值

    executorService.execute(new Runnable() {
      @Override
      public void run() {
        //复用了第一个线程池里的线程
        System.out.println(inheritableThreadLocal.get());//i am a inherit parent
      }
    });
  }

  public static void main2() throws InterruptedException {

    ExecutorService executorService = Executors.newFixedThreadPool(1);

    inheritableThreadLocal.set("i am a inherit parent");
    executorService.execute(new Runnable() {
      @Override
      public void run() {
        System.out.println(inheritableThreadLocal.get());
        inheritableThreadLocal.set("i am a old inherit parent");// 子线程中设置新的值
      }
    });

    TimeUnit.SECONDS.sleep(1);
    inheritableThreadLocal.set("i am a new inherit parent");// 主线程设置新的值

    executorService.execute(new Runnable() {
      @Override
      public void run() {

        System.out.println(inheritableThreadLocal.get());
      }
    });
  }
}
